﻿/*
 * ip4_str.cpp
 *
 *  Created on: 2016年12月12日
 *      Author: work
 */

#include <dm/export.hpp>

#define DM_API_MISC DM_API_EXPORT

#include <dm/ip4_str.hpp>
#include <dm/string/stringlist.hpp>

namespace dm{

CIp4::CIp4(){
	for( int i=0;i<4;++i )
		m_f[i] = 0;
}

CIp4::CIp4( const char* ip ){
	set(ip);
}

CIp4::CIp4( dm::uint32 ip ){
	for( int i=0;i<4;++i ){
		m_f[i] = (ip & 0xFF);
		ip >>= 8;
	}
}

CIp4::CIp4( dm::uint8 f1,dm::uint8 f2,dm::uint8 f3,dm::uint8 f4 ){
	m_f[0] = f1;
	m_f[1] = f2;
	m_f[2] = f3;
	m_f[3] = f4;
}

CIp4::CIp4( const CIp4& ip ){
	for( int i=0;i<4;++i )
		m_f[i] = ip.m_f[i];
}

CIp4& CIp4::operator =( const CIp4& ip ){
	for( int i=0;i<4;++i )
		m_f[i] = ip.m_f[i];
	return *this;
}

bool CIp4::set( const char* ip ){
	dm::string::CStringList l;
	l.split(ip,'.');
	if( l.size()!=4 )
		return false;

	bool ok;
	for( int i=0;i<4;++i ){
		m_f[i] = l.at(i).toUint8(&ok);
		if( !ok )
			return false;
	}

	return true;
}

bool CIp4::set( dm::uint8 f1,dm::uint8 f2,dm::uint8 f3,dm::uint8 f4 ){
	m_f[0] = f1;
	m_f[1] = f2;
	m_f[2] = f3;
	m_f[3] = f4;

	return true;
}

bool CIp4::setByField( int i,dm::uint8 f ){
	if( i<0 || i>3 )
		return false;
	m_f[i] = f;
	return true;
}

bool CIp4::getFieldStr( int i,CIp4::field_str_t& s )const{
	if( i<0 || i>3 )
		return false;

	s = dm::string::CString::fromUint8(m_f[i]).c_str();
	return true;
}

bool CIp4::getStr( CIp4::ip_str_t& ip )const{
	dm::string::CString f;

	f = dm::string::CString::fromUint8(m_f[0]);

	int p = f.len();

	f.dump(ip.str());
	for( int i=1;i<4;++i ){
		ip.str()[p] = '.';
		++p;
		f = dm::string::CString::fromUint8(m_f[i]);
		f.dump(ip.str()+p);
		p += f.len();
	}

	return true;
}

}


